// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SnapObjects.Data
{
    internal abstract class SqlProcedureStatementGenerator : SqlStatementGenerator
    {
        public SqlProcedureStatementGenerator(
            ISqlStatementFactory factory,
            ISqlGenerationHelper helper,
            ITypeMapper typeMapper) : base(factory, helper, typeMapper)
        {
        }

        public override SqlSyntaxDescription Create(SqlStatement statement)
        {
            var procedure = (SqlProcedureStatement)statement;

            var tokens = this.SpliceStatement(procedure);

            var builder = new StringBuilder();

            foreach (var token in tokens)
            {
                if (token.Type == SqlTokenType.Identifier)
                {
                    builder.Append(_helper.DelimitIdentifier(token.Text));
                }
                else
                {
                    builder.Append(token.Text);
                }
            }

            var parameters = procedure.Parameters.ToDictionary(
                m => m.Key, m => _helper.GenerateParameterName(m.Key));

            return new SqlSyntaxDescription(builder.ToString(), parameters, true);
        }

        protected override IReadOnlyList<SqlToken> SpliceStatement(SqlStatement statement)
        {
            var procedure = (SqlProcedureStatement)statement;

            return procedure.Procedure.ToList();
        }
    }
}
